package day08;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.hadoop.shaded.com.google.common.base.Charsets;
import org.apache.flink.shaded.guava18.com.google.common.hash.BloomFilter;
import org.apache.flink.shaded.guava18.com.google.common.hash.Funnels;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import po.UserBehavior;

import java.sql.Timestamp;

/**
 * @Description: 布隆过滤器
 * @Author: ZYX
 * @Date: 2022/2/18 14:53
 * @Version: 1.0
 */
public class Demo02 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0],arr[1],arr[2],arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                }).filter(obj -> "pv".equalsIgnoreCase(obj.behavior))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior userBehavior, long l) {
                                        return userBehavior.timestamp;
                                    }
                                })
                )
                .keyBy(obj -> true)
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                .aggregate(new CountAgg(),new WindowResult())
                .print();

        env.execute();
    }

    public static class CountAgg implements AggregateFunction<UserBehavior, Tuple2<Long,BloomFilter<String>>,Long>{
        @Override
        public Tuple2<Long, BloomFilter<String>> createAccumulator() {
            return Tuple2.of(0L,BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8),100000,0.01));
        }

        @Override
        public Tuple2<Long, BloomFilter<String>> add(UserBehavior userBehavior, Tuple2<Long, BloomFilter<String>> longBloomFilterTuple2) {
            if (!longBloomFilterTuple2.f1.mightContain(userBehavior.userId)){
                // 将对应位置为1
                longBloomFilterTuple2.f1.put(userBehavior.userId);
                longBloomFilterTuple2.f0 += 1L;
            }
            return longBloomFilterTuple2;
        }

        @Override
        public Long getResult(Tuple2<Long, BloomFilter<String>> longBloomFilterTuple2) {
            return longBloomFilterTuple2.f0;
        }

        @Override
        public Tuple2<Long, BloomFilter<String>> merge(Tuple2<Long, BloomFilter<String>> longBloomFilterTuple2, Tuple2<Long, BloomFilter<String>> acc1) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long,String,Boolean, TimeWindow> {
        @Override
        public void process(Boolean value, Context context, Iterable<Long> iterable, Collector<String> out) throws Exception {
            Timestamp start = new Timestamp(context.window().getStart());
            Timestamp end = new Timestamp(context.window().getEnd());
            Long count = iterable.iterator().next();
            out.collect("窗口" + start + "~" + end + "的uv统计值是：" + count);
        }
    }

}
